'''
客户端，通过socket连接服务器，发送数据，接收数据
'''
import socket


class Client(object):



    def __init__(self, ip, port):
        self.ip = ip
        self.port = port
        self.client_socket  = self.connect()

    def __str__(self):
        return f'客户端IP:{self.ip},客户端端口:{self.port}'

    def connect(self):
        # 连接服务端
        server_address = (self.ip, self.port)  # 服务端地址和端口
        client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client_socket.connect(server_address)  # 连接服务端
        return client_socket

    def send(self, data):
        self.client_socket.sendall(data.encode('utf-8'))  # 发送数据


    def recv(self):
        # 接收服务端响应
        response = self.client_socket.recv(1024).decode('utf-8')
        print('服务端响应:', response)

    def close(self):
        # 关闭socket
        self.client_socket.close()

if __name__ == '__main__':
    c = Client('localhost', 999)
    c.send('hello')
    c.recv()
